<template>
  <div class="p-6">
    <div class="mb-6">
      <h1 class="text-2xl font-bold mb-2">标签管理</h1>
      <p class="text-gray-600">管理知识图谱中的标签分类和属性</p>
    </div>

    <!-- 操作区域 -->
    <a-card class="mb-4">
      <a-row justify="space-between" align="middle">
        <a-col>
          <a-space>
            <a-input-search
              v-model:value="searchText"
              placeholder="搜索标签名称或描述"
              style="width: 300px"
              @search="handleSearch"
              allow-clear
            />
            <a-select
              v-model:value="categoryFilter"
              placeholder="标签分类"
              allow-clear
              style="width: 150px"
              @change="handleFilter"
            >
              <a-select-option value="">全部分类</a-select-option>
              <a-select-option value="业务">业务</a-select-option>
              <a-select-option value="技术">技术</a-select-option>
              <a-select-option value="流程">流程</a-select-option>
              <a-select-option value="质量">质量</a-select-option>
            </a-select>
            <a-select
              v-model:value="statusFilter"
              placeholder="状态"
              allow-clear
              style="width: 120px"
              @change="handleFilter"
            >
              <a-select-option value="">全部状态</a-select-option>
              <a-select-option value="active">启用</a-select-option>
              <a-select-option value="inactive">禁用</a-select-option>
            </a-select>
          </a-space>
        </a-col>
        <a-col>
          <a-space>
            <a-button type="primary" @click="showAddModal" class="!flex !items-center">
              <PlusOutlined />
              新增标签
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>

    <!-- 批量操作栏 -->
    <a-card class="mb-4" v-if="selectedRowKeys.length > 0">
      <a-space>
        <span>已选择 {{ selectedRowKeys.length }} 项</span>
        <a-button type="primary" @click="batchEnable"> 批量启用 </a-button>
        <a-button @click="batchDisable"> 批量禁用 </a-button>
        <a-button danger @click="batchDelete"> 批量删除 </a-button>
      </a-space>
    </a-card>

    <!-- 标签表格 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="currentPageData"
        :loading="loading"
        :pagination="paginationConfig"
        :row-selection="rowSelection"
        row-key="id"
        size="middle"
        @change="handleTableChange"
        :scroll="{ y: 'calc(100vh - 500px)', x: 'max-content' }"
        :expandedRowRender="expandedRowRender"
        :rowExpandable="rowExpandable"
        bordered
      >
        <template #bodyCell="{ column, record }">
          <!-- 标签名称列 -->
          <template v-if="column.key === 'name'">
            <a-space>
              <a-tag :color="record.color">{{ record.name }}</a-tag>
              <a-tag v-if="record.children && record.children.length > 0" color="cyan" size="small">
                {{ record.children.length }} 个子标签
              </a-tag>
            </a-space>
          </template>

          <!-- 层级列 -->
          <template v-else-if="column.key === 'level'">
            <a-tag :color="getLevelColor(record.level)">
              {{ getLevelText(record.level) }}
            </a-tag>
          </template>

          <!-- 分类列 -->
          <template v-else-if="column.key === 'category'">
            <a-tag :color="getCategoryColor(record.category)">
              {{ record.category }}
            </a-tag>
          </template>

          <!-- 使用次数列 -->
          <template v-else-if="column.key === 'usageCount'">
            <a-badge :count="record.usageCount" :number-style="{ backgroundColor: '#52c41a' }" />
          </template>

          <!-- 状态列 -->
          <template v-else-if="column.key === 'status'">
            <a-switch
              v-model:checked="record.status"
              :checked-value="'active'"
              :un-checked-value="'inactive'"
              @change="toggleStatus(record)"
            />
          </template>

          <!-- 创建时间列 -->
          <template v-else-if="column.key === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>

          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="editTag(record)"> 编辑 </a-button>
              <a-button type="link" size="small" @click="viewUsage(record)"> 查看使用 </a-button>
              <a-button
                type="link"
                size="small"
                @click="addChildTag(record)"
                v-if="record.level < 3"
              >
                添加子标签
              </a-button>
              <a-dropdown>
                <a-button type="link" size="small">
                  更多
                  <DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item @click="duplicateTag(record)">复制标签</a-menu-item>
                    <a-menu-item @click="mergeTag(record)">合并标签</a-menu-item>
                    <a-menu-divider />
                    <a-menu-item @click="deleteTag(record)">
                      <span style="color: #ff4d4f">删除</span>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑标签弹窗 - 简化版 -->
    <a-modal
      v-model:open="tagModalVisible"
      :title="isEdit ? '编辑标签' : '新增标签'"
      width="500px"
      @ok="saveTag"
      :confirm-loading="loading"
    >
      <a-form :model="tagForm" layout="vertical" ref="tagFormRef">
        <!-- 质量二级标签的特殊提示 -->
        <a-alert
          v-if="isEdit && isQualitySubTag(tagForm)"
          message="质量标签提示"
          description="此标签修改将同步更新到知识图谱系统中"
          type="info"
          show-icon
          class="mb-4"
        />
        
        <a-form-item
          label="标签名称"
          name="name"
          :rules="[{ required: true, message: '请输入标签名称' }]"
        >
          <a-input
            v-model:value="tagForm.name"
            placeholder="请输入标签名称"
            :maxlength="20"
            show-count
          />
        </a-form-item>

        <!-- 新增时显示更多选项 -->
        <template v-if="!isEdit">
          <a-form-item
            label="标签分类"
            name="category"
            :rules="[{ required: true, message: '请选择标签分类' }]"
          >
            <a-select v-model:value="tagForm.category" placeholder="请选择标签分类">
              <a-select-option v-for="cat in categoryOptions" :key="cat" :value="cat">
                {{ cat }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="父级标签" name="parentId">
            <a-tree-select
              v-model:value="tagForm.parentId"
              :tree-data="parentTagOptions"
              placeholder="请选择父级标签（可选）"
              allow-clear
              tree-default-expand-all
            />
          </a-form-item>

          <a-form-item label="标签颜色" name="color">
            <a-space>
              <a-input v-model:value="tagForm.color" placeholder="#1890ff" style="width: 120px" />
              <div
                v-for="color in presetColors"
                :key="color"
                :style="{
                  width: '24px',
                  height: '24px',
                  backgroundColor: color,
                  cursor: 'pointer',
                  border: tagForm.color === color ? '2px solid #000' : '1px solid #d9d9d9',
                }"
                @click="tagForm.color = color"
              ></div>
            </a-space>
          </a-form-item>

          <a-form-item label="标签描述" name="description">
            <a-textarea
              v-model:value="tagForm.description"
              :rows="3"
              placeholder="请输入标签描述"
              :maxlength="100"
              show-count
            />
          </a-form-item>
        </template>

        <!-- 编辑时显示只读信息 -->
        <template v-else>
          <a-form-item label="标签信息">
            <a-descriptions :column="1" size="small">
              <a-descriptions-item label="分类">
                <a-tag :color="getCategoryColor(tagForm.category)">
                  {{ tagForm.category }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="层级">
                <a-tag :color="getLevelColor(tagForm.level)">
                  {{ getLevelText(tagForm.level) }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="使用次数">
                {{ tagForm.usageCount }}
              </a-descriptions-item>
              <a-descriptions-item label="创建时间">
                {{ tagForm.createTime }}
              </a-descriptions-item>
            </a-descriptions>
          </a-form-item>
        </template>

        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="tagForm.status">
            <a-radio value="active">启用</a-radio>
            <a-radio value="inactive">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 使用详情弹窗 -->
    <a-modal v-model:open="usageModalVisible" title="标签使用详情" width="800px" :footer="null">
      <div v-if="currentTag">
        <a-descriptions :column="2" bordered class="mb-4">
          <a-descriptions-item label="标签名称">
            <a-tag :color="currentTag.color">{{ currentTag.name }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="使用次数">
            {{ currentTag.usageCount }}
          </a-descriptions-item>
          <a-descriptions-item label="分类">
            {{ currentTag.category }}
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="currentTag.status === 'active' ? 'success' : 'default'">
              {{ currentTag.status === 'active' ? '启用' : '禁用' }}
            </a-tag>
          </a-descriptions-item>
        </a-descriptions>

        <h4>使用记录</h4>
        <a-table :columns="usageColumns" :data-source="usageData" :pagination="false" size="small">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'entityType'">
              <a-tag>{{ record.entityType }}</a-tag>
            </template>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { PlusOutlined, DownOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { h } from 'vue'
import { Table, Tag, Switch, Button } from 'ant-design-vue'
import { getNeoLabels, updateLabels } from '@/api/api.js'

// 响应式数据
const loading = ref(false)
const searchText = ref('')
const categoryFilter = ref('')
const statusFilter = ref('')
const selectedRowKeys = ref([])
const tagModalVisible = ref(false)
const usageModalVisible = ref(false)
const isEdit = ref(false)
const currentTag = ref(null)
const tagFormRef = ref()

// 表单数据
const tagForm = ref({
  id: null,
  name: '',
  color: '#1890ff',
  category: '',
  description: '',
  status: 'active',
  level: 1,
  parentId: null,
})

// 预设颜色
const presetColors = [
  '#1890ff',
  '#52c41a',
  '#faad14',
  '#f5222d',
  '#722ed1',
  '#13c2c2',
  '#eb2f96',
  '#fa541c',
  '#a0d911',
  '#2f54eb',
]

// 表格列配置
const columns = [
  Table.EXPAND_COLUMN,
  {
    title: '标签名称',
    dataIndex: 'name',
    key: 'name',
    width: 250,
  },
  {
    title: '层级',
    dataIndex: 'level',
    key: 'level',
    width: 100,
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    width: 120,
    filters: [
      { text: '业务', value: '业务' },
      { text: '技术', value: '技术' },
      { text: '流程', value: '流程' },
      { text: '质量', value: '质量' },
    ],
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true,
  },
  {
    title: '使用次数',
    dataIndex: 'usageCount',
    key: 'usageCount',
    width: 100,
    sorter: true,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 120,
    sorter: true,
  },
  {
    title: '操作',
    key: 'action',
    width: 280,
    fixed: 'right',
  },
]

// 使用详情表格列
const usageColumns = [
  { title: '实体名称', dataIndex: 'entityName', key: 'entityName' },
  { title: '实体类型', dataIndex: 'entityType', key: 'entityType', width: 100 },
  { title: '文档来源', dataIndex: 'source', key: 'source' },
  { title: '使用时间', dataIndex: 'usedTime', key: 'usedTime', width: 120 },
]

// 模拟真实的标签数据
const tableData = ref([
  {
    id: 1,
    name: '质量',
    color: '#f5222d',
    category: '业务',
    description: '质量相关的标签分类',
    usageCount: 245,
    status: 'active',
    level: 1,
    parentId: null,
    createTime: '2025-01-15',
    children: [
      {
        id: 11,
        name: '根本原因',
        color: '#fa541c',
        category: '业务',
        description: '问题的根本原因分析',
        usageCount: 89,
        status: 'active',
        level: 2,
        parentId: 1,
        createTime: '2025-01-14',
        children: [],
      },
      {
        id: 12,
        name: '故障类别',
        color: '#fa8c16',
        category: '业务',
        description: '故障的分类标识',
        usageCount: 67,
        status: 'active',
        level: 2,
        parentId: 1,
        createTime: '2025-01-14',
        children: [],
      },
      {
        id: 13,
        name: '故障现象',
        color: '#faad14',
        category: '业务',
        description: '故障的外在表现',
        usageCount: 54,
        status: 'active',
        level: 2,
        parentId: 1,
        createTime: '2025-01-14',
        children: [],
      },
      {
        id: 14,
        name: '零件名称',
        color: '#fadb14',
        category: '业务',
        description: '相关零部件的名称',
        usageCount: 35,
        status: 'active',
        level: 2,
        parentId: 1,
        createTime: '2025-01-14',
        children: [],
      },
    ],
  },
  {
    id: 2,
    name: '法规',
    color: '#52c41a',
    category: '业务',
    description: '法规相关的标签分类',
    usageCount: 178,
    status: 'active',
    level: 1,
    parentId: null,
    createTime: '2025-01-15',
    children: [],
  },
  {
    id: 3,
    name: '工艺',
    color: '#1890ff',
    category: '技术',
    description: '工艺相关的标签分类',
    usageCount: 134,
    status: 'active',
    level: 1,
    parentId: null,
    createTime: '2025-01-15',
    children: [],
  },
  {
    id: 4,
    name: '工程',
    color: '#722ed1',
    category: '技术',
    description: '工程相关的标签分类',
    usageCount: 156,
    status: 'active',
    level: 1,
    parentId: null,
    createTime: '2025-01-15',
    children: [],
  },
  {
    id: 5,
    name: '管理',
    color: '#eb2f96',
    category: '管理',
    description: '管理相关的标签分类',
    usageCount: 98,
    status: 'active',
    level: 1,
    parentId: null,
    createTime: '2025-01-15',
    children: [],
  },
  {
    id: 6,
    name: '检测',
    color: '#13c2c2',
    category: '质量',
    description: '检测相关的标签分类',
    usageCount: 87,
    status: 'active',
    level: 1,
    parentId: null,
    createTime: '2025-01-15',
    children: [],
  },
])

// 更新标签分类选项
const categoryOptions = ['业务', '技术', '管理', '质量']

// 父级标签选项（用于下拉选择）
const parentTagOptions = computed(() => {
  const buildTreeOptions = (data, level = 1) => {
    return data
      .filter((item) => item.level === level)
      .map((item) => ({
        title: item.name,
        value: item.id,
        key: item.id,
        children:
          item.children && item.children.length > 0
            ? buildTreeOptions(item.children, level + 1)
            : undefined,
      }))
  }
  return buildTreeOptions(flattenTableData.value)
})

// 扁平化数据（用于搜索和筛选）
const flattenTableData = computed(() => {
  const flatten = (data) => {
    let result = []
    data.forEach((item) => {
      result.push(item)
      if (item.children && item.children.length > 0) {
        result = result.concat(flatten(item.children))
      }
    })
    return result
  }
  return flatten(tableData.value)
})

// 行展开渲染函数
const expandedRowRender = (record, index, indent = 0) => {
  if (!record.children || record.children.length === 0) return null

  const childColumns = [
    {
      title: '子标签名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      customRender: ({ record: childRecord }) => {
        const indentLevel = indent + 1
        return h(
          'div',
          {
            class: 'flex items-center space-x-2',
            style: { paddingLeft: `${indentLevel * 20}px` },
          },
          [
            h(Tag, { color: childRecord.color }, () => childRecord.name),
            h('span', childRecord.name),
            childRecord.children && childRecord.children.length > 0
              ? h(
                  Tag,
                  { color: 'cyan', size: 'small' },
                  () => `${childRecord.children.length} 个子标签`,
                )
              : null,
          ],
        )
      },
    },
    { title: '层级', dataIndex: 'level', key: 'level', width: 80 },
    { title: '描述', dataIndex: 'description', key: 'description', ellipsis: true },
    { title: '使用次数', dataIndex: 'usageCount', key: 'usageCount', width: 100 },
    { title: '状态', key: 'status', width: 80 },
    { title: '操作', key: 'action', width: 200 },
  ]

  return h(
    'div',
    {
      class: 'nested-table',
      style: {
        marginLeft: `${indent * 16}px`,
        borderLeft: indent > 0 ? '2px solid #f0f0f0' : 'none',
        paddingLeft: indent > 0 ? '16px' : '0',
      },
    },
    [
      h(
        Table,
        {
          columns: childColumns,
          dataSource: record.children,
          pagination: false,
          size: 'small',
          rowKey: 'id',
          showHeader: false, // 关键：隐藏表头
          expandedRowRender: (childRecord) =>
            childRecord.children && childRecord.children.length > 0
              ? expandedRowRender(childRecord, 0, indent + 1)
              : null,
          rowExpandable: (childRecord) => childRecord.children && childRecord.children.length > 0,
        },
        {
          bodyCell: ({ column, record: childRecord }) => {
            if (column.key === 'level') {
              return h(Tag, { color: getLevelColor(childRecord.level) }, () =>
                getLevelText(childRecord.level),
              )
            }
            if (column.key === 'status') {
              return h(Switch, {
                checked: childRecord.status === 'active',
                checkedValue: 'active',
                unCheckedValue: 'inactive',
                onChange: () => toggleStatus(childRecord),
              })
            }
            if (column.key === 'action') {
              return h('div', { class: 'space-x-2' }, [
                h(
                  Button,
                  { type: 'link', size: 'small', onClick: () => editTag(childRecord) },
                  () => '编辑',
                ),
                h(
                  Button,
                  { type: 'link', size: 'small', onClick: () => viewUsage(childRecord) },
                  () => '查看使用',
                ),
                childRecord.level < 3
                  ? h(
                      Button,
                      { type: 'link', size: 'small', onClick: () => addChildTag(childRecord) },
                      () => '添加子标签',
                    )
                  : null,
              ])
            }
            return childRecord[column.dataIndex]
          },
        },
      ),
    ],
  )
}

// 行是否可展开
const rowExpandable = (record) => {
  return record.children && record.children.length > 0
}

// 添加子标签
const addChildTag = (parentRecord) => {
  isEdit.value = false
  tagForm.value = {
    id: null,
    name: '',
    color: '#1890ff',
    category: parentRecord.category,
    description: '',
    status: 'active',
    level: parentRecord.level + 1,
    parentId: parentRecord.id,
  }
  tagModalVisible.value = true
}

// 获取层级颜色
const getLevelColor = (level) => {
  const colors = {
    1: 'blue',
    2: 'green',
    3: 'orange',
  }
  return colors[level] || 'default'
}

// 获取层级文本
const getLevelText = (level) => {
  const texts = {
    1: '一级',
    2: '二级',
    3: '三级',
  }
  return texts[level] || '未知'
}

// 使用详情数据
const usageData = ref([
  { entityName: '张三', entityType: '发起人', source: '问题报告.pdf', usedTime: '2025-01-15' },
  {
    entityName: '华为公司',
    entityType: '供应商',
    source: '供应链管理手册.pdf',
    usedTime: '2025-01-14',
  },
  {
    entityName: '芯片组件',
    entityType: '零部件',
    source: '产品规格书.xlsx',
    usedTime: '2025-01-13',
  },
])

// 排序和筛选状态
const sortField = ref('')
const sortOrder = ref('')
const tableFilters = ref({})

// 筛选后的数据
const filteredData = computed(() => {
  let data = [...tableData.value]

  // 搜索筛选
  if (searchText.value) {
    data = data.filter(
      (item) => item.name.includes(searchText.value) || item.description.includes(searchText.value),
    )
  }

  // 分类筛选
  if (categoryFilter.value) {
    data = data.filter((item) => item.category === categoryFilter.value)
  }

  // 状态筛选
  if (statusFilter.value) {
    data = data.filter((item) => item.status === statusFilter.value)
  }

  // 表头筛选
  Object.keys(tableFilters.value).forEach((key) => {
    const filterValues = tableFilters.value[key]
    if (filterValues && filterValues.length > 0) {
      data = data.filter((item) => filterValues.includes(item[key]))
    }
  })

  // 排序
  if (sortField.value && sortOrder.value) {
    data.sort((a, b) => {
      const aVal = a[sortField.value]
      const bVal = b[sortField.value]

      if (sortField.value === 'createTime') {
        const aTime = new Date(aVal).getTime()
        const bTime = new Date(bVal).getTime()
        return sortOrder.value === 'ascend' ? aTime - bTime : bTime - aTime
      }

      if (sortField.value === 'usageCount') {
        return sortOrder.value === 'ascend' ? aVal - bVal : bVal - aVal
      }

      if (typeof aVal === 'string') {
        return sortOrder.value === 'ascend' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal)
      }

      return sortOrder.value === 'ascend' ? aVal - bVal : bVal - aVal
    })
  }

  return data
})

// 分页配置
const paginationConfig = reactive({
  current: 1,
  pageSize: 10,
  total: computed(() => filteredData.value.length),
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
})

// 当前页显示的数据
const currentPageData = computed(() => {
  const start = (paginationConfig.current - 1) * paginationConfig.pageSize
  const end = start + paginationConfig.pageSize
  return filteredData.value.slice(start, end)
})

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  },
}

// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

const handleTableChange = (pagination, filters, sorter) => {
  console.log('表格变化:', { pagination, filters, sorter })

  // 更新分页
  paginationConfig.current = pagination.current
  paginationConfig.pageSize = pagination.pageSize

  // 更新筛选
  tableFilters.value = filters

  // 更新排序
  sortField.value = sorter.field || ''
  sortOrder.value = sorter.order || ''
}

const refreshData = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    message.success('数据刷新成功')
  }, 1000)
}

const showAddModal = () => {
  isEdit.value = false
  tagForm.value = {
    id: null,
    name: '',
    color: '#1890ff',
    category: '业务',
    description: '',
    status: 'active',
    level: 1,
    parentId: null,
  }
  tagModalVisible.value = true
}

const editTag = (record) => {
  isEdit.value = true
  tagForm.value = { ...record }
  tagModalVisible.value = true
} // 修改新增/编辑标签弹窗，只允许修改标签名

const saveTag = async () => {
  try {
    await tagFormRef.value.validate()

    if (isEdit.value) {
      // 编辑逻辑
      if (isQualitySubTag(tagForm.value)) {
        // 质量下的二级标签需要调用接口更新
        await updateQualitySubTag(tagForm.value)
      } else {
        // 其他标签前端直接更新
        updateTagLocally(tagForm.value)
      }
    } else {
      // 新增逻辑保持不变
      await addNewTag()
    }

    tagModalVisible.value = false
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

const toggleStatus = (record) => {
  message.success(`标签 ${record.name} 已${record.status === 'active' ? '启用' : '禁用'}`)
}

const viewUsage = (record) => {
  currentTag.value = record
  usageModalVisible.value = true
}

const deleteTag = async (record) => {
  if (isQualitySubTag(record)) {
    // 质量下的二级标签需要调用接口删除
    await deleteQualitySubTag(record)
  } else {
    // 其他标签前端直接删除
    deleteTagLocally(record)
  }
}

const duplicateTag = (record) => {
  const newTag = {
    ...record,
    id: Date.now(),
    name: record.name + '_副本',
    usageCount: 0,
    createTime: new Date().toISOString().split('T')[0],
  }
  tableData.value.unshift(newTag)
  message.success('标签复制成功')
}

const mergeTag = (record) => {
  message.info('合并标签功能开发中...')
}

const batchEnable = () => {
  selectedRowKeys.value.forEach((id) => {
    const item = tableData.value.find((item) => item.id === id)
    if (item) item.status = 'active'
  })
  message.success(`批量启用 ${selectedRowKeys.value.length} 个标签`)
  selectedRowKeys.value = []
}

const batchDisable = () => {
  selectedRowKeys.value.forEach((id) => {
    const item = tableData.value.find((item) => item.id === id)
    if (item) item.status = 'inactive'
  })
  message.success(`批量禁用 ${selectedRowKeys.value.length} 个标签`)
  selectedRowKeys.value = []
}

const batchDelete = () => {
  selectedRowKeys.value.forEach((id) => {
    const index = tableData.value.findIndex((item) => item.id === id)
    if (index > -1) {
      tableData.value.splice(index, 1)
    }
  })
  message.success(`批量删除 ${selectedRowKeys.value.length} 个标签`)
  selectedRowKeys.value = []
}

const getCategoryColor = (category) => {
  const colors = {
    业务: 'blue',
    技术: 'green',
    流程: 'purple',
    质量: 'orange',
  }
  return colors[category] || 'default'
}

const formatDate = (dateStr) => {
  return dateStr
}

// 动态标签数据
const dynamicLabels = ref([])

// 获取动态标签并更新表格数据
const fetchAndUpdateLabels = async () => {
  try {
    const res = await getNeoLabels()
    if (res.code === 200) {
      dynamicLabels.value = res.data
      updateTableDataWithDynamicLabels()
    }
  } catch (error) {
    console.error('获取标签失败:', error)
  }
}

// 根据动态标签更新表格数据
const updateTableDataWithDynamicLabels = () => {
  // 找到质量标签
  const qualityTag = tableData.value.find((tag) => tag.name === '质量')
  if (qualityTag) {
    // 清空现有子标签
    qualityTag.children = []

    // 根据动态标签创建子标签
    const colors = ['#fa541c', '#fa8c16', '#faad14', '#fadb14']
    dynamicLabels.value.forEach((label, index) => {
      qualityTag.children.push({
        id: 10 + index + 1,
        name: label,
        color: colors[index % colors.length],
        category: '业务',
        description: `${label}相关标签`,
        usageCount: Math.floor(Math.random() * 100) + 20,
        status: 'active',
        level: 2,
        parentId: 1,
        createTime: '2025-01-14',
        children: [],
      })
    })
  }
}

// 判断是否为质量下的二级标签
const isQualitySubTag = (record) => {
  return record.level === 2 && record.parentId === 1 // 质量标签的ID是1
}

// 更新质量下的二级标签（调用接口）
const updateQualitySubTag = async (tagData) => {
  try {
    loading.value = true
    
    // 找到要更新的标签的原始名称
    const oldName = tableData.value
      .find(tag => tag.name === '质量')
      ?.children?.find(child => child.id === tagData.id)?.name
    
    if (oldName && oldName !== tagData.name) {
      // 调用接口更新单个标签
      const res = await updateLabels({
        old_label: oldName,
        new_label: tagData.name
      })
      
      if (res.code === 200) {
        // 更新本地动态标签数据
        const index = dynamicLabels.value.indexOf(oldName)
        if (index !== -1) {
          dynamicLabels.value[index] = tagData.name
        }
        
        // 更新表格数据
        updateTableDataWithDynamicLabels()
        message.success('质量标签更新成功')
      } else {
        message.error('标签更新失败：' + res.msg)
      }
    } else if (oldName === tagData.name) {
      // 如果名称没有变化，只更新状态
      const updateItem = (data, targetId, newData) => {
        for (let item of data) {
          if (item.id === targetId) {
            item.status = newData.status
            return true
          }
          if (item.children && updateItem(item.children, targetId, newData)) {
            return true
          }
        }
        return false
      }
      updateItem(tableData.value, tagData.id, tagData)
      message.success('标签状态更新成功')
    }
  } catch (error) {
    console.error('更新质量标签失败:', error)
    message.error('标签更新失败，请重试')
  } finally {
    loading.value = false
  }
}

// 本地更新标签（非质量二级标签）
const updateTagLocally = (tagData) => {
  const updateItem = (data, targetId, newData) => {
    for (let item of data) {
      if (item.id === targetId) {
        // 只更新允许修改的字段
        item.name = newData.name
        item.status = newData.status
        return true
      }
      if (item.children && updateItem(item.children, targetId, newData)) {
        return true
      }
    }
    return false
  }
  
  updateItem(tableData.value, tagData.id, tagData)
  message.success('标签更新成功')
}

// 新增标签逻辑
const addNewTag = async () => {
  const newTag = {
    ...tagForm.value,
    id: Date.now(),
    usageCount: 0,
    createTime: new Date().toISOString().split('T')[0],
    children: [],
    level: tagForm.value.parentId ? 2 : 1,
  }

  if (tagForm.value.parentId === 1) {
    // 如果是添加到质量标签下，需要调用接口
    try {
      loading.value = true
      const updatedLabels = [...dynamicLabels.value, tagForm.value.name]
      
      const res = await updateLabels(updatedLabels)
      
      if (res.code === 200) {
        dynamicLabels.value = updatedLabels
        updateTableDataWithDynamicLabels()
        message.success('质量子标签创建成功')
      } else {
        message.error('标签创建失败：' + res.msg)
      }
    } catch (error) {
      console.error('创建质量标签失败:', error)
      message.error('标签创建失败，请重试')
    } finally {
      loading.value = false
    }
  } else {
    // 其他标签直接添加到本地
    if (tagForm.value.parentId) {
      const addToParent = (data, parentId, newItem) => {
        for (let item of data) {
          if (item.id === parentId) {
            if (!item.children) item.children = []
            item.children.push(newItem)
            return true
          }
          if (item.children && addToParent(item.children, parentId, newItem)) {
            return true
          }
        }
        return false
      }
      addToParent(tableData.value, tagForm.value.parentId, newTag)
    } else {
      tableData.value.push(newTag)
    }
    message.success('标签创建成功')
  }
}

// 删除质量下的二级标签（调用接口）
const deleteQualitySubTag = async (record) => {
  try {
    loading.value = true
    
    // 如果删除接口需要特定格式，可以调用删除接口
    // 这里假设删除是通过更新标签列表实现的
    const updatedLabels = dynamicLabels.value.filter(label => label !== record.name)
    
    // 如果有专门的删除接口，可以这样调用：
    // const res = await deleteLabel({ label: record.name })
    
    // 目前通过更新整个标签列表来实现删除
    const res = await updateLabels(updatedLabels)
    
    if (res.code === 200) {
      dynamicLabels.value = updatedLabels
      updateTableDataWithDynamicLabels()
      message.success('质量标签删除成功')
    } else {
      message.error('标签删除失败：' + res.msg)
    }
  } catch (error) {
    console.error('删除质量标签失败:', error)
    message.error('标签删除失败，请重试')
  } finally {
    loading.value = false
  }
}

// 本地删除标签
const deleteTagLocally = (record) => {
  const deleteFromData = (data, targetId) => {
    for (let i = 0; i < data.length; i++) {
      if (data[i].id === targetId) {
        data.splice(i, 1)
        return true
      }
      if (data[i].children && deleteFromData(data[i].children, targetId)) {
        return true
      }
    }
    return false
  }
  
  deleteFromData(tableData.value, record.id)
  message.success('标签删除成功')
}

// 在组件挂载时获取标签
onMounted(() => {
  fetchAndUpdateLabels()
})
</script>

<style lang="scss" scoped>
.p-6 {
  padding: 24px;
}

.mb-6 {
  margin-bottom: 24px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mb-2 {
  margin-bottom: 8px;
}

.text-2xl {
  font-size: 24px;
}

.font-bold {
  font-weight: bold;
}

.text-gray-600 {
  color: #666;
}

// 嵌套表格样式
:deep(.nested-table) {
  .ant-table {
    margin-bottom: 0;

    .ant-table-tbody > tr > td {
      border-bottom: 1px solid #f0f0f0;
      background-color: #fafafa;
    }

    .ant-table-thead > tr > th {
      background-color: #f5f5f5;
      font-size: 12px;
      padding: 8px 16px;
    }

    .ant-table-tbody > tr > td {
      padding: 8px 16px;
      font-size: 12px;
    }
  }

  // 不同层级的背景色
  &:nth-child(1) .ant-table-tbody > tr > td {
    background-color: #fafafa;
  }

  &:nth-child(2) .ant-table-tbody > tr > td {
    background-color: #f0f0f0;
  }

  &:nth-child(3) .ant-table-tbody > tr > td {
    background-color: #e6f7ff;
  }
}

// 层级连接线样式
:deep(.ant-table-expanded-row) {
  .nested-table {
    position: relative;

    &::before {
      content: '';
      position: absolute;
      left: -8px;
      top: 0;
      bottom: 0;
      width: 2px;
      background: linear-gradient(to bottom, #d9d9d9 0%, #d9d9d9 50%, transparent 50%);
    }
  }
}

:deep(.nt-table-expanded-row-fixed){
display: none !important;
}
</style>






